package com.qf.config;

import com.alibaba.fastjson.JSONObject;
import com.qf.pojo.respVo.BaseResp;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
@Component //交给spring管理
public class MyInterceptor implements HandlerInterceptor {

    @Autowired
    RedisTemplate redisTemplate;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取token
        String token = request.getHeader("token");
        Boolean aBoolean = redisTemplate.hasKey(RedisKey.LOGIN_KEY + token);
        //如没有token,说明用户未登录
        if (!aBoolean){
        writeResponse(response,new BaseResp().Fail(0,"用户未登录!"));
        }
        //如果用户是登录状态,需要给用户增加用户登录的有效时长
        redisTemplate.expire(RedisKey.LOGIN_KEY+token,300, TimeUnit.SECONDS);
        return true;
    }

    public void writeResponse(HttpServletResponse response, BaseResp baseResp){
        response.setContentType("application/json");
        response.setCharacterEncoding("utf-8");
        try {
            response.getWriter().write(JSONObject.toJSONString(baseResp));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
